<template>
  <div class="script-management-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h1>漏洞扫描脚本管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="showCreateScriptDialog" icon="el-icon-plus">
          创建脚本
        </el-button>
        <el-button @click="refreshScripts" icon="el-icon-refresh">
          刷新列表
        </el-button>
        <el-dropdown @command="handleBatchAction">
          <el-button>
            批量操作
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="batchDelete">批量删除</el-dropdown-item>
              <el-dropdown-item command="batchEnable">批量启用</el-dropdown-item>
              <el-dropdown-item command="batchDisable">批量禁用</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchQuery"
            placeholder="搜索脚本名称或描述"
            prefix-icon="el-icon-search"
            clearable
            @input="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="scriptTypeFilter"
            placeholder="按类型筛选"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="SQL注入" value="sql_injection" />
            <el-option label="XSS" value="xss" />
            <el-option label="命令注入" value="command_injection" />
            <el-option label="CSRF" value="csrf" />
            <el-option label="信息泄露" value="information_disclosure" />
            <el-option label="未授权访问" value="unauthorized_access" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="scriptStatusFilter"
            placeholder="按状态筛选"
            clearable
            @change="handleFilterChange"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="resetFilters">
            重置筛选
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 脚本列表表格 -->
    <el-card class="script-table-container" shadow="hover">
      <el-table
        v-loading="isLoading"
        :data="filteredScripts"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="脚本名称" show-overflow-tooltip>
          <template #default="scope">
            <span @click="viewScriptDetails(scope.row)" class="clickable-text">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="脚本类型" width="120">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="severity" label="严重程度" width="100">
          <template #default="scope">
            <el-tag :type="getSeverityTagType(scope.row.severity)">
              {{ getSeverityText(scope.row.severity) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="toggleScriptStatus(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="160" />
        <el-table-column prop="updated_at" label="更新时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="showEditScriptDialog(scope.row)"
              icon="el-icon-edit"
              circle
              title="编辑脚本"
            />
            <el-button
              type="danger"
              size="small"
              @click="confirmDeleteScript(scope.row)"
              icon="el-icon-delete"
              circle
              title="删除脚本"
            />
            <el-button
              size="small"
              @click="viewScriptDetails(scope.row)"
              icon="el-icon-view"
              circle
              title="查看详情"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页控件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑脚本对话框 -->
    <el-dialog
      v-model="scriptDialogVisible"
      :title="isEditMode ? '编辑脚本' : '创建脚本'"
      width="800px"
      :close-on-click-modal="false"
      @close="closeScriptDialog"
    >
      <el-form
        ref="scriptFormRef"
        :model="scriptForm"
        :rules="scriptFormRules"
        label-width="120px"
        class="script-form"
      >
        <el-form-item label="脚本名称" prop="name">
          <el-input v-model="scriptForm.name" placeholder="请输入脚本名称" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="脚本类型" prop="type">
          <el-select v-model="scriptForm.type" placeholder="请选择脚本类型">
            <el-option label="SQL注入" value="sql_injection" />
            <el-option label="XSS" value="xss" />
            <el-option label="命令注入" value="command_injection" />
            <el-option label="CSRF" value="csrf" />
            <el-option label="信息泄露" value="information_disclosure" />
            <el-option label="未授权访问" value="unauthorized_access" />
            <el-option label="配置错误" value="configuration_error" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="严重程度" prop="severity">
          <el-select v-model="scriptForm.severity" placeholder="请选择严重程度">
            <el-option label="严重" value="critical" />
            <el-option label="高危" value="high" />
            <el-option label="中危" value="medium" />
            <el-option label="低危" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="scriptForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入脚本描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="脚本内容" prop="content">
          <el-input
            v-model="scriptForm.content"
            type="textarea"
            :rows="15"
            placeholder="请输入Python脚本内容"
            class="monospace-textarea"
          />
          <div class="form-tip">
            请按照脚本规范编写Python代码，确保包含必要的函数和元数据
          </div>
        </el-form-item>
        <el-form-item label="启用状态" prop="status">
          <el-switch
            v-model="scriptForm.status"
            active-value="enabled"
            inactive-value="disabled"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeScriptDialog">取消</el-button>
          <el-button type="primary" @click="submitScriptForm">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
          <el-button @click="getScriptTemplate" v-if="!isEditMode">
            获取模板
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 脚本详情对话框 -->
    <el-dialog
      v-model="scriptDetailDialogVisible"
      title="脚本详情"
      width="900px"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="activeDetailTab">
        <el-tab-pane label="基本信息">
          <div class="detail-section">
            <div class="detail-row">
              <div class="detail-label">脚本ID：</div>
              <div class="detail-value">{{ selectedScript.id }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">脚本名称：</div>
              <div class="detail-value">{{ selectedScript.name }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">脚本类型：</div>
              <div class="detail-value">{{ getTypeText(selectedScript.type) }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">严重程度：</div>
              <div class="detail-value">{{ getSeverityText(selectedScript.severity) }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">状态：</div>
              <div class="detail-value">
                <el-tag :type="selectedScript.status === 'enabled' ? 'success' : 'danger'">
                  {{ selectedScript.status === 'enabled' ? '启用' : '禁用' }}
                </el-tag>
              </div>
            </div>
            <div class="detail-row">
              <div class="detail-label">创建时间：</div>
              <div class="detail-value">{{ selectedScript.created_at }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">更新时间：</div>
              <div class="detail-value">{{ selectedScript.updated_at }}</div>
            </div>
            <div class="detail-row">
              <div class="detail-label">描述：</div>
              <div class="detail-value description-content">{{ selectedScript.description }}</div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="脚本代码">
          <pre class="script-code">{{ selectedScript.content }}</pre>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 脚本上传对话框 -->
    <el-dialog
      v-model="uploadDialogVisible"
      title="上传脚本"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-upload
        class="upload-demo"
        drag
        action=""
        :before-upload="handleScriptUpload"
        :file-list="uploadFileList"
        :auto-upload="false"
        accept=".py"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将Python脚本拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">
            只能上传.py文件，单个文件大小不超过2MB
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeUploadDialog">取消</el-button>
          <el-button type="primary" @click="submitUpload">
            开始上传
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, ArrowDown, Edit, Delete, View } from '@element-plus/icons-vue'
import apiService from '../services/apiService'

// 组件状态
const isLoading = ref(false)
const scripts = ref([])
const searchQuery = ref('')
const scriptTypeFilter = ref('')
const scriptStatusFilter = ref('')
const selectedScripts = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const activeDetailTab = ref('0')

// 对话框状态
const scriptDialogVisible = ref(false)
const scriptDetailDialogVisible = ref(false)
const uploadDialogVisible = ref(false)
const isEditMode = ref(false)

// 表单数据
const scriptForm = reactive({
  id: '',
  name: '',
  type: '',
  description: '',
  content: '',
  severity: '',
  status: 'enabled'
})

const selectedScript = ref({})
const uploadFileList = ref([])

// 表单验证规则
const scriptFormRules = {
  name: [
    { required: true, message: '请输入脚本名称', trigger: 'blur' },
    { min: 3, max: 100, message: '脚本名称长度在 3 到 100 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择脚本类型', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入脚本描述', trigger: 'blur' },
    { min: 5, max: 500, message: '脚本描述长度在 5 到 500 个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入脚本内容', trigger: 'blur' }
  ],
  severity: [
    { required: true, message: '请选择严重程度', trigger: 'change' }
  ]
}

// 表单引用
const scriptFormRef = ref(null)

// 计算过滤后的脚本列表
const filteredScripts = computed(() => {
  let result = [...scripts.value]
  
  // 按名称或描述搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(script => 
      script.name.toLowerCase().includes(query) || 
      script.description.toLowerCase().includes(query)
    )
  }
  
  // 按类型过滤
  if (scriptTypeFilter.value) {
    result = result.filter(script => script.type === scriptTypeFilter.value)
  }
  
  // 按状态过滤
  if (scriptStatusFilter.value) {
    result = result.filter(script => script.status === scriptStatusFilter.value)
  }
  
  total.value = result.length
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  
  return result.slice(start, end)
})

// 初始化
onMounted(() => {
  loadScripts()
})

// 加载脚本列表
const loadScripts = async () => {
  isLoading.value = true
  try {
    // 调用API获取脚本列表，根据过滤条件决定是否只显示启用的脚本
    const filterEnabled = scriptStatusFilter.value === 'enabled' || scriptStatusFilter.value === ''
    const getScriptsFn = apiService.getScripts(filterEnabled)
    const response = await getScriptsFn()
    scripts.value = response.data || []
  } catch (error) {
    console.error('加载脚本失败:', error)
    ElMessage.error('加载脚本失败')
  } finally {
    isLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
}

// 筛选条件变化
const handleFilterChange = () => {
  currentPage.value = 1
}

// 重置筛选条件
const resetFilters = () => {
  searchQuery.value = ''
  scriptTypeFilter.value = ''
  scriptStatusFilter.value = ''
  currentPage.value = 1
}

// 刷新脚本列表
const refreshScripts = () => {
  loadScripts()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedScripts.value = selection
}

// 批量操作
const handleBatchAction = (command) => {
  if (selectedScripts.value.length === 0) {
    ElMessage.warning('请先选择要操作的脚本')
    return
  }
  
  switch (command) {
    case 'batchDelete':
      confirmBatchDelete()
      break
    case 'batchEnable':
      batchEnableScripts()
      break
    case 'batchDisable':
      batchDisableScripts()
      break
  }
}

// 显示创建脚本对话框
const showCreateScriptDialog = () => {
  isEditMode.value = false
  resetScriptForm()
  scriptDialogVisible.value = true
}

// 显示编辑脚本对话框
const showEditScriptDialog = (script) => {
  isEditMode.value = true
  Object.assign(scriptForm, script)
  scriptDialogVisible.value = true
}

// 关闭脚本对话框
const closeScriptDialog = () => {
  scriptDialogVisible.value = false
  resetScriptForm()
}

// 重置脚本表单
const resetScriptForm = () => {
  scriptForm.id = ''
  scriptForm.name = ''
  scriptForm.type = ''
  scriptForm.description = ''
  scriptForm.content = ''
  scriptForm.severity = ''
  scriptForm.status = 'enabled'
  
  if (scriptFormRef.value) {
    scriptFormRef.value.resetFields()
  }
}

// 提交脚本表单
const submitScriptForm = async () => {
  if (!scriptFormRef.value) return
  
  try {
    await scriptFormRef.value.validate()
    
    // 调用API提交表单数据
    if (isEditMode.value) {
      // 更新脚本
      const updateScriptFn = apiService.updateScript(scriptForm.name, scriptForm)
      await updateScriptFn()
      ElMessage.success('脚本更新成功')
      // 重新加载脚本列表以获取最新数据
      await loadScripts()
    } else {
      // 创建新脚本
      const createScriptFn = apiService.createScript(scriptForm)
      await createScriptFn()
      ElMessage.success('脚本创建成功')
      // 重新加载脚本列表以获取最新数据
      await loadScripts()
    }
    
    closeScriptDialog()
  } catch (error) {
    console.error('提交脚本表单失败:', error)
    if (!error.valid) return // 表单验证失败，不显示错误消息
    ElMessage.error('操作失败，请重试')
  }
}

// 获取脚本模板
const getScriptTemplate = async () => {
  try {
    isLoading.value = true
    // 根据表单中已选择的类型获取相应的脚本模板
    const getTemplateFn = apiService.getScriptTemplate(scriptForm.name || 'new_scan_script', scriptForm.type || 'custom')
    const response = await getTemplateFn()
    
    if (response && response.data && response.data.template) {
      scriptForm.content = response.data.template
    } else {
      ElMessage.warning('获取模板失败，使用默认模板')
      // 如果API获取失败，使用默认模板作为后备
      const defaultTemplate = `# 漏洞扫描脚本模板
# 脚本元数据
metadata = {
    'name': '${scriptForm.name || '自定义漏洞扫描器'}',
    'description': '${scriptForm.description || '请输入脚本描述'}',
    'type': '${scriptForm.type || 'custom'}',
    'severity': '${scriptForm.severity || 'medium'}',
    'author': '管理员',
    'version': '1.0',
    'created_at': '${new Date().toISOString().split('T')[0]}',
}

def scan(target):
    """执行漏洞扫描"""
    return {
        'vulnerable': False,
        'details': '',
        'payload': '',
        'evidence': '',
        'remediation': ''
    }`
      scriptForm.content = defaultTemplate
    }
  } catch (error) {
    console.error('获取脚本模板失败:', error)
    ElMessage.error('获取脚本模板失败')
  } finally {
    isLoading.value = false
  }
}

// 切换脚本状态
const toggleScriptStatus = async (script) => {
  try {
    // 准备切换到的目标状态
    const targetStatus = script.status === 'enabled' ? false : true
    
    // 调用API更新脚本状态
    const toggleStatusFn = apiService.toggleScriptStatus(script.name, targetStatus)
    await toggleStatusFn()
    
    // 重新加载脚本列表以获取最新数据
    await loadScripts()
    
    ElMessage.success(`脚本已${targetStatus ? '启用' : '禁用'}`)
  } catch (error) {
    console.error('更新脚本状态失败:', error)
    // 重新加载数据以恢复正确状态
    await loadScripts()
    ElMessage.error('操作失败，请重试')
  }
}

// 确认删除脚本
const confirmDeleteScript = (script) => {
  ElMessageBox.confirm(
    `确定要删除脚本"${script.name}"吗？此操作不可恢复。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteScript(script.name)
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除确认
const confirmBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的${selectedScripts.value.length}个脚本吗？此操作不可恢复。`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 批量删除现在通过循环单个删除实现，因为API没有批量删除端点
    Promise.all(
      selectedScripts.value.map(script => {
        const deleteScriptFn = apiService.deleteScript(script.name)
        return deleteScriptFn()
      })
    ).then(() => {
      // 重新加载脚本列表
      loadScripts()
      ElMessage.success(`已成功删除${selectedScripts.value.length}个脚本`)
      selectedScripts.value = []
    }).catch(error => {
      console.error('批量删除脚本失败:', error)
      ElMessage.error('批量删除失败，请重试')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 删除脚本
const deleteScript = async (scriptName) => {
  try {
    // 调用API删除脚本
    const deleteScriptFn = apiService.deleteScript(scriptName)
    await deleteScriptFn()
    
    // 重新加载脚本列表以更新数据
    await loadScripts()
    ElMessage.success('脚本删除成功')
  } catch (error) {
    console.error('删除脚本失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 批量删除脚本
const batchDeleteScripts = async (ids) => {
  try {
    // 这里应该调用API批量删除脚本
    // await apiService.batchDeleteScripts(ids)
    
    // 更新本地数据
    scripts.value = scripts.value.filter(script => !ids.includes(script.id))
    ElMessage.success(`已成功删除${ids.length}个脚本`)
    selectedScripts.value = []
  } catch (error) {
    console.error('批量删除脚本失败:', error)
    ElMessage.error('批量删除失败，请重试')
  }
}

// 批量启用脚本
const batchEnableScripts = async () => {
  try {
    isLoading.value = true
    
    // 批量启用通过循环单个启用实现，因为API没有批量启用端点
    await Promise.all(
      selectedScripts.value.map(script => {
        const toggleStatusFn = apiService.toggleScriptStatus(script.name, true)
        return toggleStatusFn()
      })
    )
    
    // 重新加载脚本列表
    await loadScripts()
    
    ElMessage.success(`已成功启用${selectedScripts.value.length}个脚本`)
    selectedScripts.value = []
  } catch (error) {
    console.error('批量启用脚本失败:', error)
    ElMessage.error('批量启用失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 批量禁用脚本
const batchDisableScripts = async () => {
  try {
    isLoading.value = true
    
    // 批量禁用通过循环单个禁用实现，因为API没有批量禁用端点
    await Promise.all(
      selectedScripts.value.map(script => {
        const toggleStatusFn = apiService.toggleScriptStatus(script.name, false)
        return toggleStatusFn()
      })
    )
    
    // 重新加载脚本列表
    await loadScripts()
    
    ElMessage.success(`已成功禁用${selectedScripts.value.length}个脚本`)
    selectedScripts.value = []
  } catch (error) {
    console.error('批量禁用脚本失败:', error)
    ElMessage.error('批量禁用失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 查看脚本详情
const viewScriptDetails = async (script) => {
  try {
    isLoading.value = true
    // 调用API获取脚本详情，获取完整信息
    const getScriptFn = apiService.getScript(script.name)
    const response = await getScriptFn()
    
    if (response && response.data) {
      selectedScript.value = { ...response.data }
    } else {
      // 如果API调用失败，使用本地数据作为后备
      selectedScript.value = { ...script }
    }
    
    scriptDetailDialogVisible.value = true
  } catch (error) {
    console.error('获取脚本详情失败:', error)
    // 如果API调用失败，使用本地数据作为后备
    selectedScript.value = { ...script }
    scriptDetailDialogVisible.value = true
  } finally {
    isLoading.value = false
  }
}

// 处理脚本上传
const handleScriptUpload = (file) => {
  uploadFileList.value = [file]
  return false // 阻止自动上传
}

// 提交上传
const submitUpload = async () => {
  if (uploadFileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  
  const file = uploadFileList.value[0]
  const formData = new FormData()
  formData.append('script_file', file)
  
  try {
    isLoading.value = true
    
    // 使用axios直接上传文件（因为我们没有专门的uploadScript方法）
    // 注意：这里可能需要根据实际API调整
    const response = await apiService.api.post('/scripts/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    ElMessage.success('脚本上传成功')
    closeUploadDialog()
    await loadScripts() // 重新加载脚本列表以获取最新数据
  } catch (error) {
    console.error('上传脚本失败:', error)
    ElMessage.error('上传失败，请重试')
  } finally {
    isLoading.value = false
  }
}

// 关闭上传对话框
const closeUploadDialog = () => {
  uploadDialogVisible.value = false
  uploadFileList.value = []
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (current) => {
  currentPage.value = current
}

// 辅助方法：获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    'sql_injection': 'SQL注入',
    'xss': 'XSS',
    'command_injection': '命令注入',
    'csrf': 'CSRF',
    'information_disclosure': '信息泄露',
    'unauthorized_access': '未授权访问',
    'configuration_error': '配置错误',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 辅助方法：获取类型标签样式
const getTypeTagType = (type) => {
  const typeTagMap = {
    'sql_injection': 'danger',
    'xss': 'warning',
    'command_injection': 'danger',
    'csrf': 'warning',
    'information_disclosure': 'info',
    'unauthorized_access': 'danger',
    'configuration_error': 'warning',
    'other': 'default'
  }
  return typeTagMap[type] || 'default'
}

// 辅助方法：获取严重程度文本
const getSeverityText = (severity) => {
  const severityMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return severityMap[severity] || severity
}

// 辅助方法：获取严重程度标签样式
const getSeverityTagType = (severity) => {
  const severityTagMap = {
    'critical': 'danger',
    'high': 'warning',
    'medium': 'info',
    'low': 'success'
  }
  return severityTagMap[severity] || 'default'
}
</script>

<style scoped>
.script-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-filter-container {
  background: #fff;
  padding: 20px;
  border-radius: 6px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.script-table-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.clickable-text {
  cursor: pointer;
  color: #409eff;
  text-decoration: underline;
}

.clickable-text:hover {
  color: #66b1ff;
}

.script-form {
  margin-top: 10px;
}

.monospace-textarea {
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
}

.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.detail-section {
  padding: 10px 0;
}

.detail-row {
  display: flex;
  margin-bottom: 15px;
}

.detail-label {
  width: 100px;
  font-weight: 500;
  color: #606266;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-word;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.5;
}

.script-code {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  max-height: 500px;
  overflow-y: auto;
  line-height: 1.6;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}

@media (max-width: 768px) {
  .script-management-container {
    padding: 10px;
  }
  
  .search-filter-container {
    padding: 15px;
  }
  
  .search-filter-container .el-row {
    flex-direction: column;
  }
  
  .search-filter-container .el-col {
    width: 100% !important;
    margin-bottom: 10px;
  }
  
  .script-dialog .el-dialog {
    width: 95% !important;
  }
  
  .detail-row {
    flex-direction: column;
    gap: 5px;
  }
  
  .detail-label {
    width: auto;
  }
}
</style>